<?php

class firstPage extends CI_Controller
{
	/*构造函数,初始化,自动运行调用一些方法*/ // 百度到的:创建一个新的 SimpleXMLElement 对象
	public function __construct()
	{
		header("Content-type:text/html;charset=utf-8");
		parent::__construct();

		$this->load->database();
		$this->load->model('home/entries_model','en');
		$this->load->model('home/user');

		$this->load->library('form_validation');// 类库
		$this->load->library('session');        // 启用session
		$this->load->library('pagination');     // 启用分页

		$this->load->helper(array('form', 'url','captcha','date','download')); //辅助函数

		// 先判断用户是否登录
		$methods = array('listResult','userList');
		$this->deal_session($methods);
	}

	public function index(){}

	// 用于处理用户是否登录
	public function deal_session($methods)
	{
		foreach($methods as $v)
		{
			if(method_exists($this,$v) && $this->session->userdata('username')){
				continue;
			}else{
				redirect(base_url());
			}
		}
	}

	public function listResult()
	{
		intval($this->input->get('per_page',1)) ? $page = intval($this->input->get('per_page',1)) : $page = 1;
		$searchColumns = array('title','content','type'); // 以后添加搜索字段就在这里了
		$searchArr = array();
		$searchStr = 'firstPage/listResult?';
		foreach($_GET as $k => $v){
			$v = trim($v);
			if(in_array($k, $searchColumns)){
				$searchArr[$k] = $v;
				$searchStr .= "&$k=$v";
			}
		}
		$url = base_url($searchStr);

		$config['base_url'] = $url;
		$config['per_page'] = 10;
		$config['num_links'] = 2;
		$config['use_page_numbers'] = TRUE;
		$config['page_query_string'] = TRUE;
		$config['enable_query_strings'] = TRUE;
		$config['total_rows'] = $this->en->count($searchArr);
		$config['next_link'] = '下一页';
		$config['next_tag_open'] = '<li aria-label="Next"><span aria-hidden="true">';
		$config['next_tag_close'] = '</span></li>';
		$config['prev_link'] = '上一页';
		$config['prev_tag_open'] = '<li aria-label="Previous"><span aria-hidden="true">';
		$config['prev_tag_close'] = '</span></li>';
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = '<li class="active"><span class="sr-only">';
		$config['cur_tag_close'] = '</span></li>';
		$config['last_link'] = '末页';
		$config['last_tag_open'] = '<li aria-label="Next"><span aria-hidden="true">';
		$config['last_tag_close'] = '</span></li>';
		$config['first_link'] = '首页';
		$config['first_tag_open'] = '<li aria-label="Next"><span aria-hidden="true">';
		$config['first_tag_close'] = '</span></li>';
		$config['anchor_class'] = 'class = "ajax_page" ';

		$offset = ($page - 1) * $config['per_page']; // 设置偏移量
		$result = $this->en->fuzzy_search($searchArr, $offset, $config['per_page']);
		// 判断是否为搜索并且还有搜索结果
		if(empty($result) && $this->input->get('searchKey'))
		{
			$data['error'] = '你搜索的词汇不存在,请重新输入!';
		}

		$this->pagination->initialize($config);
		$data['pag']    = $this->pagination->create_links();
		// ID换成name,并给ajax部分赋值
		foreach($result as $k => $v)
		{
			$uId = $v['userId'];
			$name = $this->user->someOne2($uId);
			$result[$k]['userId'] = $name['username'];
			$result[$k]['pag']    = $data['pag'];     // 把分页条放进$result
			$result[$k]['url']    = base_url("firstPage/show?id=".$result[$k]['eId']); // 每篇文章的URL
			$result[$k]['givePower'] = 0;             // 有没有操作的权利
			if(($this->session->userdata('username')==$result[$k]['userId'])||($this->session->userdata('authority')==1))
			{
				$result[$k]['givePower'] = 1;
			}
		}
		$data['result'] = $result;

		if($page > 1)
		{
			return print(json_encode($result));
		}

		$data['title']     = $this->input->get('title');
		$data['username']  = $this->session->userdata('username');
		$data['authority'] = $this->session->userdata('authority') == 0 ? '普通会员':'管理员';
		$data['backInfo']  = $this->session->userdata('backInfo'); // 反馈信息,如:删除文章是否成功
		$this->session->unset_userdata('backInfo');

		$this->load->view('mainPage/content',$data);

	}

	// 用户列表
	public function userList()
	{
		// 用户列表分页
		$page = intval($this->input->get('per_page',1)) ? intval($this->input->get('per_page',1)) : 1;

		if($this->session->userdata('authority') == 1)
		{
			// 判断是搜索还是列表
			if($this->input->post('searchKey')) // 用户名是唯一的,就不用分页了
			{
				$name = trim($this->input->post('name'));
				$data['result'] = $this->user->listUser(0,1,$name);
				if(empty($data['result'])){
					$data['result'] = '此用户不存在';
				}
			}else{
				$config['base_url']             = base_url('firstPage/userList?');
				$config['per_page']             = 5;
				$config['num_links']            = 2;
				$config['use_page_numbers']     = TRUE;
				$config['page_query_string']    = TRUE;
				$config['enable_query_strings'] = TRUE;
				$config['cur_tag_open']         = '<b>';
				$config['cur_tag_close']        = '</b>';
				$config['total_rows']           = $this->user->count();
				$config['next_link']            = '下一页';
				$config['next_tag_open']        = '<li aria-label="Next"><span aria-hidden="true">';
				$config['next_tag_close']       = '</span></li>';
				$config['prev_link']            = '上一页';
				$config['prev_tag_open']        = '<li aria-label="Previous"><span aria-hidden="true">';
				$config['prev_tag_close']       = '</span></li>';
				$config['num_tag_open']         = '<li>';
				$config['num_tag_close']        = '</li>';
				$config['cur_tag_open']         = '<li class="active"><span class="sr-only">';
				$config['cur_tag_close']        = '</span></li>';
				$config['anchor_class']         = 'class="ajax_page" ';

				$offset = ($page - 1 ) * $config['per_page']; // 设置偏移量
				$name = 0;
				$result = $this->user->listUser($offset, $config['per_page'],$name);
				$data['result'] = $result;
				$this->pagination->initialize($config);
				$data['pag']    = $this->pagination->create_links();
			}
		}else{
			$data['result'] = '您无权查看其他用户信息!';
		}

		if($page>1)
		{
			foreach($result as $k => $v)
			{
				$result[$k]['pag'] = $data['pag']; // 传分页条
				$result[$k]['upURL'] = base_url("userController/upOthers?id=".$result[$k]['userId']); // 传修改其他用户的URL
				$result[$k]['delURL'] = base_url("userController/del?id=".$result[$k]['userId']);     // 传删除用户的URL
				$result[$k]['preAuthor'] = $this->session->userdata('authority');
			}
			return print(json_encode($result));
		}

		$data['username']  = $this->session->userdata('username');
		$data['authority'] = $this->session->userdata('authority') == 0 ? '普通会员':'管理员';
		$data['backInfo']  = $this->session->userdata('backInfo'); // 显示反馈信息,例如:删除用户情况
		$this->session->unset_userdata('backInfo');

		$this->load->view('mainPage/userList',$data);
	}

	// 显示文章
	public function show()
	{
		$eId = trim($this->input->get('id'));

		//查出文章有关信息
		$msg = $this->en->get_entries($eId);
		$name = $this->user->someOne2($msg['userId']);
		$msg['userId'] = $name['username'];
		$msg['username']  = $this->session->userdata('username');
		$msg['authority'] = $this->session->userdata('authority') == 0 ? '普通会员':'管理员';
		$this->load->view('mainPage/show',$msg);
	}

	// 添加更新数据
	public function add()
	{
		$eId = $this->input->get('id');

		$config = array(
			array(
				'field' => 'title',
				'label' => '标题',
				'rules' => 'trim|required|min_length[2]|xss_clean'
			),
			array(
				'field' => 'content',
				'label' => '内容',
				'rules' => 'required'
			),
		);
		$this->form_validation->set_rules($config);

		// 设置错误信息
		$this->form_validation->set_message('required','%s不能为空');
		$this->form_validation->set_message('min_length[2]','%s至少为2个字符');

		if($_POST)
		{
			if($this->form_validation->run() == true) // 开始验证
			{
				// 规范传值
				$dataTmp = array(
					'title'   => $this->input->post('title'),
					'content' => $this->input->post('content'),
					'userId'  => $this->session->userdata('userId')
				);
				if($eId){
					$result = $this->en->update($eId,$dataTmp);
				} else{
					$result = $this->en->insert($dataTmp);
				}

				if($result)
				{
					redirect(base_url('firstPage/listResult'),'refresh');
				}else{
					echo '操作失败!';
					exit;
				}
			}
		}
		$data['username']  = $this->session->userdata('username');
		$data['authority'] = $this->session->userdata('authority') == 0 ? '普通会员':'管理员';
		if($eId){
			$data['result']    = $this->en->get_entries($eId);
			$name              = $this->user->someOne2($data['result']['userId']);
			$data['result']['author'] = $name['username'];
			$data['id']        = $eId;
		}

		$this->load->view('mainPage/add',$data);
	}

	// 更新数据
	public function up()
	{
		// 验证规则
		$config = array(
			array(
				'field' => 'title',
				'label' => '标题',
				'rules' => 'trim|required|min_length[1]|max_length[2]|xss_clean'
			),
			array(
				'field' => 'content',
				'label' => '内容',
				'rules' => 'required'
			),
		);
		$this->form_validation->set_rules($config);

		if($_POST)
		{
			if($this->form_validation->run() == true) // 开始验证
			{
				// 规范传值
				$dataTmp = array(
					'title'   => $this->input->post('title'),
					'content' => $this->input->post('content')
				);

				$result = $this->en->update($eId,$dataTmp);

				if($result)
				{
					redirect(base_url('firstPage/listResult'),'refresh');
				}else{
					echo '修改失败!';
					exit;
				}
			}
		}
		$data['username']  = $this->session->userdata('username');
		$data['authority'] = $this->session->userdata('authority');
		$data['result'] = $this->en->get_entries($eId);
		$this->load->view('mainPage/add',$data);
	}

	// 删除数据
	public function del()
	{
		$eId = $this->input->get('id');
		if($eId){
			$result = $this->en->delete($eId);
		}
		if($result){
			$this->session->set_userdata('backInfo','删除成功');
		} else{
			$this->session->set_userdata('backInfo','删除失败');
		}

		redirect('firstPage/listResult'); // 返回首页
	}

}